package com.ftg.learn.controller;

import dev.langchain4j.community.model.dashscope.WanxImageModel;
import dev.langchain4j.data.image.Image;
import dev.langchain4j.model.output.Response;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;

/**
 * @author 布衣
 */
@RestController
@RequestMapping("/img")
public class TextToImageController {


    @Autowired
    private WanxImageModel wanxImageModel;

    @Autowired
    HttpServletResponse resp;

    @GetMapping("/generate")
    public String generate(@RequestParam("prompt") String prompt) {
        Response<Image> response = wanxImageModel.generate(prompt);
        return response.content().url().toString();
    }

    @GetMapping(value = "/create", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] create(@RequestParam("prompt") String prompt) throws IOException {
        Response<Image> response = wanxImageModel.generate(prompt);
        // 解码Base64数据并返回字节数组
        return new URL(response.content().url().toString()).openStream().readAllBytes();
    }
}
